const path = require("path");
const fs = require("fs");
const _ = require("lodash");
const {
  readAllValues,
} = require("../awakened-potential/helpers/readAllValues.js");
const { calcAccuracySummary } = require("./calcAccuracySummary");
const select32Numbers = require("./select32Numbers.js");

const esm = require("esm");
const requireModule = esm(module);
const { flatGroupMap, groupArray } = requireModule(
  "../awakened-potential/helpers/readGroup.js"
);
const getNumberGroupMap = require("../awakened-potential/modules/cjs/getNumberGroupMap.js");
const checkAccuracy = require("./checkAccuracy.js");

const allNumbers = Array.from({ length: 49 }, (_, i) => i + 1).map((n) =>
  n < 10 ? `0${n}` : `${n}`
);
const numberGroupMap = getNumberGroupMap(allNumbers, flatGroupMap);
const historyData = readAllValues("m") // .slice(0, 500);
const historyNumbers = historyData.map((item) => item.number);
const slidingPairs = _.range(0, historyNumbers.length - 1).map((i) =>
  historyNumbers.slice(i, i + 2)
);

// 生成 groupAccuracyMap：groupName => [0/1,...]
const groupAccuracyMap = _.mapValues(flatGroupMap, (v, key) =>
  slidingPairs.map(([prev, curr]) => {
    const subIndex = numberGroupMap[prev][key];
    const subGroup = flatGroupMap[key][subIndex];
    return checkAccuracy(subGroup, curr);
  })
);

// 设置参数
const useWindow = true;
const windowSize = 200;
const outputPath = path.join(__dirname, "result.jsonl"); // 每行为一条 JSON
fs.writeFileSync(outputPath, ""); // 清空文件

// 统计变量
let accurateCount = 0;
let totalCount = 0;
// 新增变量用于错误段统计
let maxConsecutiveErrors = 0;
let currentConsecutiveErrors = 0;
let errorStreaks = []; // 每段错误 streak 的长度

// 主循环 + 存储分离
for (let i = windowSize; i < historyData.length; i++) {
  const item = historyData[i];
  const lastNumber = historyData[i - 1].number;

  const killNextAccuracyMap = _.mapValues(groupAccuracyMap, (value) =>
    useWindow ? value.slice(i - windowSize - 1, i - 1) : value.slice(0, i - 1)
  );

  const stats = Object.entries(killNextAccuracyMap).map(([key, arr]) => ({
    key,
    value: calcAccuracySummary(arr),
  }));

  const lucky_array = select32Numbers(
    stats,
    flatGroupMap,
    numberGroupMap,
    lastNumber,
    { maxAllowConsecutiveIncorrect: 2 }
  );
  const isAccurate = checkAccuracy(lucky_array, item.number);

  totalCount++;
  if (isAccurate === 1) {
    accurateCount++;

    if (currentConsecutiveErrors > 0) {
      errorStreaks.push(currentConsecutiveErrors);
      if (currentConsecutiveErrors > maxConsecutiveErrors) {
        maxConsecutiveErrors = currentConsecutiveErrors;
      }
      currentConsecutiveErrors = 0;
    }
  } else {
    currentConsecutiveErrors++;
  }

  fs.appendFileSync(
    outputPath,
    JSON.stringify({
      index: i,
      date: item.time,
      number: item.number,
      lucky_array,
      isAccurate,
    }) + "\n"
  );
}

// 最后可能还有一个未结尾的错误段
if (currentConsecutiveErrors > 0) {
  errorStreaks.push(currentConsecutiveErrors);
  if (currentConsecutiveErrors > maxConsecutiveErrors) {
    maxConsecutiveErrors = currentConsecutiveErrors;
  }
}

// 输出统计结果
console.log(`📊 准确率统计:`);
console.log(`总期数: ${totalCount}`);
console.log(`命中次数: ${accurateCount}`);
console.log(`未命中次数: ${totalCount - accurateCount}`);
console.log(`准确率: ${((accurateCount / totalCount) * 100).toFixed(2)}%`);

console.log(`\n📉 错误分析:`);
console.log(`最大连续错误: ${maxConsecutiveErrors}`);
console.log(`错误段数: ${errorStreaks.length}`);
console.log(
  `平均连续错误: ${
    errorStreaks.length
      ? (errorStreaks.reduce((a, b) => a + b, 0) / errorStreaks.length).toFixed(
          2
        )
      : 0
  }`
);
console.log(`当前连续错误: ${currentConsecutiveErrors}`);
